import { useEffect, useState, useRef } from "react";
import * as echarts from "echarts";

const Home = () => {
  const [ws, setWs] = useState(new WebSocket("ws://47.108.128.216:5000"));
  let timer = null;
  const [option, setOption] = useState({
    title: {
      text: "用户访问量统计",
    },
    tooltip: {},
    xAxis: {
      data: ["2024-1-25", "2024-1-24", "2024-1-23", "2024-1-22", "2024-1-21"],
    },
    yAxis: {},
    series: [
      {
        name: "访问量",
        type: "bar",
        data: [10, 20, 30, 40, 50],
      },
    ],
  });
  const [option2, setOption2] = useState({
    xAxis: {
      type: "category",
      data: ["2024-1-25", "2024-1-24", "2024-1-23", "2024-1-22", "2024-1-21"],
    },
    yAxis: {
      type: "value",
    },
    tooltip: {
      trigger: 'axis'
    },
    series: [
      {
        data: [150, 230, 224, 218, 135, 147, 260],
        type: "line",
      },
    ],
  });
  // useRef 用于解决 useState 获取不到最新值的问题
  const optionRef = useRef(null);
  const optionRef2 = useRef(null);
  useEffect(() => {
    optionRef.current = echarts.init(document.getElementById("main"));
    optionRef2.current = echarts.init(document.getElementById("lineChart"));
    initWs();
    getHistogram();
    getLineChart()
    return () => {
      clearInterval(timer);
      ws.close();
      setWs(null);
    };
  }, []);
  const updateOption = (newArr) => {
    let newOption = { ...option };
    let newOption2 = { ...option2 };
    newOption2.series[0].data = newArr;
    setOption2(newOption2);
    newOption.series[0].data = newArr;
    setOption(newOption);
    getHistogram();
    getLineChart();
  };
  // 绘制柱状图
  const getHistogram = () => {
    if (!optionRef.current) {
      echarts.init(document.getElementById("main")).setOption(option);
    } else {
      optionRef.current.setOption(option);
    }
  };
  // 绘制折线图
  const getLineChart = () => {
    if (!optionRef2.current) {
      echarts.init(document.getElementById("lineChart")).setOption(option2);
    } else {
      optionRef2.current.setOption(option2);
    }
  };
  const initWs = () => {
    ws.onopen = () => {
      console.log("ws连接成功");
      ws.send("ping");
      timer = setInterval(() => {
        ws.send("ping");
      }, 10000);
    };
    ws.onmessage = (event) => {
      // console.log("ws收到消息", event.data);
      let newArr = [];
      const msgData = JSON.parse(event.data);
      if (msgData.type === "userVisits") {
        msgData.msg.forEach((e) => {
          newArr.push(e.num);
        });
        updateOption(newArr);
      }
    };
    ws.onclose = (e) => {
      console.log("ws连接关闭");
      console.log(
        "websocket 断开: " + e.code + " " + e.reason + " " + e.wasClean
      );
      clearInterval(timer);
      initWs();
    };
  };
  return (
    <div>
      <div id="main" style={{ width: "100%", height: "500px" }}></div>
      <div id="lineChart" style={{ width: "100%", height: "500px" }}></div>
    </div>
  );
};

export default Home;
